﻿using EntitySpaces.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using yncTech.BusinessObjects;
using yncTech.Common;

public partial class Admin_Fin_Fin007a : AdminBasePage
{
    decimal lendID = -1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString[VLendBoxMetadata.ColumnNames.LendID] != null)
        {
            lendID = decimal.Parse(Request.QueryString[VLendBoxMetadata.ColumnNames.LendID]);
        }
        if (!IsPostBack)
        {
            switch (ActionType)
            {
                case OperationType.Add:
                    txtRetDate.Value = DateTime.Now.AddDays(7).ToString(ConstantValue.DateFormat);
                    btnSave.Text = "新增";
                    break;
                case OperationType.Update:

                    FinLend fld = new FinLend();
                    fld.LoadByPrimaryKey(lendID);

                    txtLoanee.Text = fld.Loanee;
                    txtLoaneeMail.Text = fld.LoaneeEmail;
                    txtRetDate.Value = fld.ReturnDate.Value.ToString(ConstantValue.DateFormat);
                    txtComments.Text = fld.Comments;
                    txtFile.Text = fld.Attachment;
                    btnSave.Text = "修改";
                    break;
                case OperationType.Delete:
                case OperationType.Confirm:
                case OperationType.Return:
                    btnSave_Click(null, null);
                    break;
            }
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string fileName = string.Empty;
        lbMessage.Text = "";
        if (fileUpload.HasFile)
        {
            try
            {
                fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileUpload.FileName);
                string filePath = Server.MapPath("/UploadFile/") + fileName;
                fileUpload.SaveAs(filePath);

                txtFile.Text = fileName;
            }
            catch (Exception ex)
            {
                lbMessage.Text = ex.Message;
            }
        }
        else
        {
            lbMessage.Text = "请选择要上传的文件!";
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtFile.Text.Trim().Length == 0)
            {
                if (ActionType == OperationType.Add || ActionType == OperationType.Update)
                {
                    lbMessage.Text = "请上传申请文件!";
                    return;
                }
            }
            FinLend fld = new FinLend();
            switch (ActionType)
            {
                case OperationType.Add:
                    //fld.ThirdUnitID = LoginUserInfo.CurrentUser.ThirdUnitID;
                    //fld.LendDate = DateTime.Now;
                    fld.Loanee = txtLoanee.Text;
                    fld.LoaneeEmail = txtLoaneeMail.Text;
                    fld.ReturnDate = DateTime.Parse(txtRetDate.Value);
                    //fld.LendStatus = (int)LendStatus.Pending;
                    fld.Comments = txtComments.Text;
                    fld.Attachment = txtFile.Text;
                    fld.CreatedBy = fld.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                    fld.CreatedDttm = fld.UpdatedDttm = DateTime.Now;
                    fld.Save();
                    break;
                case OperationType.Update:
                    fld.LoadByPrimaryKey(lendID);
                    fld.Loanee = txtLoanee.Text;
                    fld.LoaneeEmail = txtLoaneeMail.Text;
                    fld.ReturnDate = DateTime.Parse(txtRetDate.Value);
                    fld.Comments = txtComments.Text;
                    fld.Attachment = txtFile.Text;
                    fld.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                    fld.UpdatedDttm = DateTime.Now;
                    fld.Save();
                    break;
                case OperationType.Delete:
                    try
                    {
                        using (esTransactionScope tr = new esTransactionScope())
                        {
                            FinLendBoxCollection lendBoxes = new FinLendBoxCollection();
                            lendBoxes.Query.Where(lendBoxes.Query.LendID == lendID);
                            lendBoxes.Query.Load();
                            var boxIDs = lendBoxes.Select(r => r.LendBoxID.Value).ToArray();
                            lendBoxes.MarkAllAsDeleted();
                            lendBoxes.Save();

                            if (boxIDs.Length > 0)
                            {
                                FinBoxCollection finBoxes = new FinBoxCollection();
                                finBoxes.Query.Where(finBoxes.Query.BoxID.In(boxIDs));
                                finBoxes.Query.Load();

                                foreach (var item in finBoxes)
                                {
                                    item.StorageStatus = ConstantValue.StorageStatusCode.InStock;
                                    item.UpdatedDttm = DateTime.Now;
                                    item.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                                }
                                finBoxes.Save();
                            }
                            FinLend fl = new FinLend();
                            fl.LoadByPrimaryKey(lendID);
                            fl.MarkAsDeleted();
                            fl.Save();
                            tr.Complete();
                        }
                        WebHelper.GotoParent();
                    }
                    catch (Exception ex)
                    {
                        WebHelper.GotoParent(ex.Message);
                    }
                    break;
                case OperationType.Confirm:
                    FinLend flend = new FinLend();
                    flend.LoadByPrimaryKey(lendID);
                    //flend.LendStatus = (int)LendStatus.Lent;
                    flend.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                    flend.UpdatedDttm = DateTime.Now;
                    flend.Save();
                    WebHelper.GotoParent();
                    break;
                case OperationType.Return:
                    try
                    {
                        using (esTransactionScope tr = new esTransactionScope())
                        {
                            FinLendReceiptCollection lendReceipts = new FinLendReceiptCollection();
                            lendReceipts.Query.Where(lendReceipts.Query.LendID == lendID);
                            lendReceipts.Query.Load();
                            var receiptIDs = lendReceipts.Select(r => r.ReceiptID.Value).ToArray();



                            FinReceiptCollection finReceipts = new FinReceiptCollection();
                            finReceipts.Query.Where(finReceipts.Query.ReceiptID.In(receiptIDs));
                            finReceipts.Query.Load();

                            if (finReceipts.Count > 0)
                            {
                                
                                foreach (var item in finReceipts)
                                {
                                    item.StorageStatus = ConstantValue.StorageStatusCode.InStock;
                                    item.UpdatedDttm = DateTime.Now;
                                    item.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                                }
                                finReceipts.Save();

                                var boxIDs = finReceipts.Where(r => r.BoxID.Value > 0).Select(r => r.BoxID).Distinct().ToList();
                                ///凭证归还后检查凭证盒中是否还有外借的凭证，如没有，则将状态改为在库
                                FinLendReceiptQuery q1 = new FinLendReceiptQuery("q1");
                                FinBoxReceiptsQuery q2 = new FinBoxReceiptsQuery("q2");
                                FinLendQuery q3 = new FinLendQuery("q3");

                                q1.InnerJoin(q2).On(q1.ReceiptID == q2.ReceiptID);
                                q1.InnerJoin(q3).On(q1.LendID == q3.LendID);
                                q1.Where(q2.BoxID.In(boxIDs.ToArray()) && (q3.LendStatus == (int)LendStatus.Lent || q3.LendStatus == (int)LendStatus.Pending));
                                q1.Select(q2.BoxID);
                                var boxs = q1.LoadDataTable();

                                List<decimal> tempList = new List<decimal>();
                                for (int i = 0; i < boxs.Rows.Count; i++)
                                {
                                    decimal tmpID = (decimal)boxs.Rows[i][0];
                                    if (boxIDs.Exists(r => r == tmpID))
                                    {
                                        tempList.Add(tmpID);
                                    }
                                }

                                if (tempList.Count > 0)
                                {
                                    FinBoxCollection boxCollection = new FinBoxCollection();
                                    boxCollection.Query.Where(boxCollection.Query.BoxID.In(tempList.ToArray()));
                                    boxCollection.Query.Load();

                                    foreach (var box in boxCollection)
                                    {
                                        box.StorageStatus = ConstantValue.StorageStatusCode.InStock;
                                        box.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                                        box.UpdatedDttm = DateTime.Now;
                                    }
                                    boxCollection.Save();
                                }

                            }

                            FinLend fl = new FinLend();
                            fl.LoadByPrimaryKey(lendID);
                            //fl.LendStatus = (int)LendStatus.Returned;
                            fl.ActReturnDate = DateTime.Now;

                            fl.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                            fl.UpdatedDttm = DateTime.Now;
                            fl.Save();
                            tr.Complete();
                        }
                        WebHelper.GotoParent();
                    }
                    catch (Exception ex)
                    {
                        WebHelper.GotoParent(ex.Message);
                    }
                    break;

            }
            WebHelper.CloseDialog(true);
        }
        catch (Exception ex)
        {
            lbMessage.Text = ex.Message;
        }
    }
}